use rusqlite::params;

use crate::dao;
use crate::models::models::components::v2ray::router::ComponentV2rayRouter;
use crate::runtime::error::MagicBoxError;
use crate::runtime::response::Code;
use crate::runtime::result::MagicBoxResult;

/// 添加路由
pub(crate) fn add_router(router: ComponentV2rayRouter) -> MagicBoxResult<()> {
    let connection = dao::connection::components::v2ray();

    let mut statement = connection.prepare("insert into routers (uuid, `type`, domain_or_ip_rule, preset) values (?1, ?2, ?3, ?4)").unwrap();
    let result = statement.execute(params![router.uuid, router._type, router.domain_or_ip_rule, router.preset]);
    if result.is_err() {
        let err = result.unwrap_err().to_string();
        log::error!("添加路由失败: {}", err.as_str());

        return Err(MagicBoxError::new(Code::UndefinedError, format!("添加路由失败: {}", err.as_str()).as_str()));
    }

    Ok(())
}

/// 移除路由
pub(crate) fn remove_router(uuid: String) -> MagicBoxResult<()> {
    let connection = dao::connection::components::v2ray();

    let mut statement = connection.prepare("delete from routers where uuid = ?1").unwrap();
    let result = statement.execute(params![uuid]);
    if result.is_err() {
        let err = result.unwrap_err().to_string();
        log::error!("删除路由失败: {}", err.as_str());

        return Err(MagicBoxError::new(Code::UndefinedError, format!("删除路由失败: {}", err.as_str()).as_str()));
    }

    Ok(())
}

/// 获取服务器列表
pub(crate) fn get_all_routers() -> MagicBoxResult<Vec<ComponentV2rayRouter>> {
    let connection = dao::connection::components::v2ray();
    let mut routers: Vec<ComponentV2rayRouter> = Vec::new();

    let mut statement = connection.prepare("select * from routers order by id desc").unwrap();
    let result = statement.query_map([], parse_to_router);

    if result.is_err() {
        let err = result.err().unwrap().to_string();
        log::error!("获取路由列表失败: {}", err.as_str());

        return Err(MagicBoxError::new(Code::UndefinedError, format!("获取路由列表失败: {}", err.as_str()).as_str()));
    }

    let result = result.unwrap();
    for router in result {
        if router.is_err() {
            let err = router.err().unwrap().to_string();
            log::error!("获取路由失败: {}", err.as_str());

            return Err(MagicBoxError::new(Code::UndefinedError, format!("获取路由失败: {}", err.as_str()).as_str()));
        }

        routers.push(router.unwrap());
    }

    Ok(routers)
}

/// 解析路由配置
fn parse_to_router(row: &rusqlite::Row) -> rusqlite::Result<ComponentV2rayRouter> {
    let mut router = ComponentV2rayRouter::default();

    router.uuid = row.get::<_, String>(1)?;
    router._type = row.get::<_, String>(2)?;
    router.domain_or_ip_rule = row.get::<_, String>(3)?;
    router.preset = row.get::<_, bool>(4)?;

    Ok(router)
}